import { useState, useEffect } from "react";
import { Form, Alert, message, Select } from "antd";
import CommonModal from "@/components/CommonModal";
import Typography from "@/pages/OrderModule/common/components/Typography";
import { reassignReturnClerk, queryTakeUserList } from "../service";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";

const ReturnSupplier = ({ handleCancel, returnClerkParams, fetchList }) => {

	const [form] = Form.useForm();
	const [userData, setUserData] = useState([]); // 拿货员列表
  const [open, setOpen] = useState(false);
  const [isOk, setIsOk] = useState(false);

  //获取退货员列表
	const handleUserList = async () => {
		const { data, success } = await queryTakeUserList({
			current: 1,
			size: 2000,
			businessType: 4,
		});
		if (success) {
			if (data) {
				const list = data.map(v => {
          return {
            label: v.name + "(" + v.account + ")",
            value: v.id
          }
				});
				setUserData([{ label: '原有退货员', value: 0 }, ...list]);
			}
		}
	};

	useEffect(() => {
		handleUserList();
		setOpen(true);
	}, []);

  //点击确定
	const onOk = () => {
		form.validateFields().then(async value => {
      START_LOADING();
      const pickerId = value.pickerId;
      const pickerName = userData.filter(v => v.value == pickerId)[0].label;
      const uniqueCode = returnClerkParams.map(v => v.uniqueCode).join();
			const { success } = await reassignReturnClerk({
				pickerId,
				uniqueCode,
				pickerName
			});
      END_LOADING();
			if (success) {
				message.success("操作成功");
				setIsOk(true);
        setOpen(false);
			}
		});
	};

	const onCancel = () => {
		setOpen(false);
	};

  const afterClose = () => {
    if(isOk) {
      fetchList();
    }
    handleCancel();
  }

	return (
		<CommonModal 
      title="继续退供" 
      open={open} 
      onOk={onOk} 
      onCancel={onCancel}
      afterClose={afterClose}
      width="553px" 
    >
			<Alert showIcon message={<Typography as="s1">将所选唯一码退货状态由<span className="common-color9">拒绝退货、商户拒绝</span>变更为<span className="common-color9">待退货</span>，并重新指定退货员执行退货任务</Typography>} />
			<SubTitle symbol as="s2" title="指派退货员" wrapStyle={{ marginBottom: 16, marginTop: 20 }} />
			<Form 
        form={form} 
        name="return-supplier-modal" 
        initialValues={{ pickerId: 0 }}
        style={{ marginTop: "12px" }}
      >
				<Form.Item label="" name="pickerId" rules={[{ required: true, message: "请选择退货员" }]}>
					<Select showSearch placeholder="请选择退货员" allowClear options={userData}></Select>
				</Form.Item>
			</Form>
		</CommonModal>
	);
};

export default ReturnSupplier;
